// 基于准备好的dom，初始化echarts实例
var myMap = echarts.init(document.getElementById('map'));

option_map = {
    title: {
        text: '像素图',
        left: 'center'
    },
    tooltip: {
        trigger: 'item'
    },
    bmap: {
        center: [123.4118195, 41.81805976],
        zoom: 13,
        roam: true,
        enableMapClick: false
    },
    visualMap: {
        type: 'piecewise',
        inverse: true,
        top: 10,
        left: 10,
        pieces: [{
            value: 0, label: '午夜商业/住宅区', color: '#e74c3c'
        }, {
            value: 1, label: '工作区', color: '#f1c40f'
        }, {
            value: 2, label: '工作区/商业区', color: '#3498db'
        }, {
            value: 3, label: '边缘区', color: '#2ecc71'
        }, {
            value: -1, label: '无', color: '#ecf0f1'
        }, {
            value: 12, label: '边界点', color: 'black'
        }],
        borderColor: '#ccc',
        borderWidth: 2,
        backgroundColor: '#eee',
        dimension: 2,
        inRange: {
            opacity: 0.7
        }
    },
    series: [
        {
            name: '定位',
            type: 'scatter',
            coordinateSystem: 'bmap',
            data: [
                [123.30603424257413, 41.742959589335406, 12, 100],
                [123.54058735124023, 41.89321074219711, 12, 100],
                [123.30603424257413, 41.89321074219711, 12, 100],
                [123.54058735124023, 41.742959589335406, 12, 100]],
            symbolSize: function (val) {
                return val[3] / 10;
            },
            encode: {
                tooltip: 3 // 鼠标碰触点显示的是value[3]
            },
            emphasis: {
                itemStyle: {
                    color: 'yellow'
                }
            }
        },
        {
            type: 'custom',
            coordinateSystem: 'bmap',
            renderItem: renderItem,
            animation: false,
            emphasis: {
                itemStyle: {
                    color: '#34495e'
                }
            },
            encode: {
                tooltip: 2
            },
            data: []
        }
    ]
};

// myMap.setOption(option_map);

// 像素图的范围和像素图的方块个数
const lngRange = [123.30603424257413, 123.54058735124023];
const latRange = [41.742959589335406, 41.89321074219711];
const cellCount = [50, 50];

function getCoord_X(longitude) {
    return parseInt((longitude - lngRange[0]) / ((lngRange[1] - lngRange[0]) / cellCount[0]));
}

function getCoord_Y(latitude) {
    return parseInt((latitude - latRange[0]) / ((latRange[1] - latRange[0]) / cellCount[0]));
}

var latExtent = [123.30603424257413, 123.45628735124023];
var lngExtent = [41.742959589335406, 41.97751074219711];
var cellSizeCoord = [
    (lngExtent[1] - lngExtent[0]) / cellCount[0], // 长
    (latExtent[1] - latExtent[0]) / cellCount[1] // 宽
];

function renderItem(params, api) {

    var lngIndex = api.value(0);
    var latIndex = api.value(1);
    var pointLeftTop = getCoord(params, api, lngIndex, latIndex);

    var pointRightBottom = getCoord(params, api, lngIndex + 1, latIndex + 1);
    return {
        type: 'rect',
        shape: {
            x: pointLeftTop[0],
            y: pointLeftTop[1],
            width: pointRightBottom[0] - pointLeftTop[0],
            height: pointRightBottom[1] - pointLeftTop[1]
        },
        style: api.style({
            stroke: 'rgba(0,0,0,0)'
        }),
        styleEmphasis: api.styleEmphasis()
    };

}

function getCoord(params, api, lngIndex, latIndex) {

    var coords = params.context.coords || (params.context.coords = []);
    var key = lngIndex + '-' + latIndex;
    // bmap returns point in integer, which makes cell width unstable.
    // So we have to use right bottom point.

    return coords[key] || (coords[key] = api.coord([
        +(latExtent[0] + lngIndex * cellSizeCoord[0]).toFixed(6),
        +(lngExtent[0] + latIndex * cellSizeCoord[1]).toFixed(6)
    ]));
}

// ----------------------- 以下为数据处理部分 -----------------------

// 全局变量
let tempArray = [];
let originData = [];
let finalData = [];
let array = [];
for (let i = 0; i < 50; i++) {
    array.push([]);
    for (let j = 0; j < 50; j++) {
        array[i].push([0, 0, 0, 0]);
    }
}

// 先从数据库获取originData
$.ajax({
    type: "GET",
    url: '/BaseStationType',
    cache: false,
    success: function (res) {
        originData = res;

        // 将originData分组放进tempArray中，每组100条数据
        let temp = [];
        for (let i = 0; i < originData.length; i++) {
            temp.push([originData[i].longitude, originData[i].latitude]);
            if (i % 100 == 99 || i == originData.length - 1) {
                tempArray.push(temp);
                temp = [];
            }
        }

        // 利用接口转换坐标
        genFinalData(0, tempArray.length);
    }
});

function genFinalData(index, length) {
    let temp = tempArray[index].join(';');
    // 利用百度接口转换坐标
    $.ajax({
        type: "GET",
        url: "http://api.map.baidu.com/geoconv/v1/?coords=" + temp + "&from=3&to=5&ak=SipXZFGUXfBvDr88wUQHGdwhP06tY5Bz",
        dataType: "jsonp",
        cache: false,
        success: function (res) {
            for (let j = 0; j < res.result.length; j++) {
                finalData.push([res.result[j].x, res.result[j].y, originData[index * 100 + j].type]);
            }
            if (++index != length) {
                // 为解决ajax异步问题使用递归
                genFinalData(index, length);
            } else {
                // 所有坐标都转换完成后生成pixels数据画出像素图
                DrawPixels();
                // 结束递归
                return;
            }
        }
    });
}

function DrawPixels() {
    for (point of finalData) {
        if (point[0] < lngRange[1] && point[0] > lngRange[0] && point[1] < latRange[1] && point[1] > latRange[0]) {
            let x = getCoord_X(point[0]);
            let y = getCoord_Y(point[1]);
            array[x][y][point[2]]++;
        }
    }

    var pixels = [];
    for (let i = 0; i < 50; i++) {
        for (let j = 0; j < 50; j++) {
            let temp = [array[i][j][0], array[i][j][1], array[i][j][2], array[i][j][3]];
            temp.sort(function (a, b) {
                return b - a;
            });
            for (index in array[i][j]) {
                if (temp[0] != 0) {
                    if (array[i][j][index] == temp[0]) {
                        pixels.push([i, j, index]);
                        break;
                    }
                } else {
                    pixels.push([i, j, -1]);
                    break;
                }
            }
        }
    }

    option_map.series[1].data = pixels;
    myMap.setOption(option_map);
}